package com.pb.camera;

import java.util.List; 

import com.pb.camera.application.App;
import com.pb.camera.lock.LockPatternUtils;
import com.pb.camera.lock.LockPatternView;
import com.pb.camera.lock.LockPatternView.Cell;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Color;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.TextView;
import android.widget.Toast;
//解锁界面
//问题在于冲那里获取以前保存的手势跟现在绘制的手势比较呢
public class UnlockGesturePasswordActivity extends Activity {
	private LockPatternView mLockPatternView;
	private int mFailedPatternAttemptsSinceLastTimeout = 0;
	private CountDownTimer mCountdownTimer = null;
	private Handler mHandler = new Handler();
	private TextView mHeadTextView;
	private TextView  text_forget_password;
	private Animation mShakeAnim;
	private Toast mToast;

	private void showToast(CharSequence message) {
		if (null == mToast) {
			mToast = Toast.makeText(this, message, Toast.LENGTH_SHORT);
			mToast.setGravity(Gravity.CENTER, 0, 0);
		} else {
			mToast.setText(message);
		}

		mToast.show();
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		  requestWindowFeature(Window.FEATURE_NO_TITLE); 

		setContentView(R.layout.gesturepassword_unlock);
		  if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
	            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
	          //  getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
	        }
		App.getInstance().getAllActivity().add(this);
		mLockPatternView = (LockPatternView) this
				.findViewById(R.id.gesturepwd_unlock_lockview);
		mLockPatternView.setOnPatternListener(mChooseNewLockPatternListener);
		mLockPatternView.setTactileFeedbackEnabled(true);
		mHeadTextView = (TextView) findViewById(R.id.gesturepwd_unlock_text);
		mShakeAnim = AnimationUtils.loadAnimation(this, R.anim.shake_x);
		text_forget_password=(TextView) findViewById(R.id.gesturepwd_unlock_forget);
		text_forget_password.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
			     Bundle  bundle=new Bundle();
			     bundle.putString("errorMessage", "1");
			     bundle.putString("whereFrom", "gesture");			     
				  Intent  intent=new Intent(UnlockGesturePasswordActivity.this,LogInActivity.class);
			      intent.putExtras(bundle);
			      startActivity(intent);
				finish();
			}
		});
	}
	@Override
	protected void onResume() {
		super.onResume();
	 
	
	}

	@Override
	protected void onDestroy() {
		App.getInstance().getAllActivity().remove(this);
		super.onDestroy();
		if (mCountdownTimer != null)
			mCountdownTimer.cancel();
	}
	private Runnable mClearPatternRunnable = new Runnable() {
		public void run() {
			mLockPatternView.clearPattern();
		}
	};
  //九宫格的响应函数
//比较两次手势的地方
	protected LockPatternView.OnPatternListener mChooseNewLockPatternListener = new 

LockPatternView.OnPatternListener() {

		public void onPatternStart() {
			mLockPatternView.removeCallbacks(mClearPatternRunnable);
			patternInProgress();
		}

		public void onPatternCleared() {
			mLockPatternView.removeCallbacks(mClearPatternRunnable);
		}
		public void onPatternDetected(List<Cell> pattern) {
			if (pattern == null)
				return;
			//但是跟谁比较的啊,怎么获取的呢
			//调用 l	App.getInstance().getLockPatternUtils

             //().saveLockPattern(mChosenPattern);
			//这里保存的手势就是后面比较的一方
			//注意必须保证是单利的util类才可以的
			  SharedPreferences  pre=getSharedPreferences("itisforlife",Context.MODE_PRIVATE);		    		  		        
		      String gesture=  pre.getString("gesture", "void");
			if (gesture.equals(App.getInstance().getLockPatternUtils().patternToString(pattern))) 
			{
				mLockPatternView.setDisplayMode(LockPatternView.DisplayMode.Correct);			
				//以后修改跳转到app的首页之类的界面
				Intent intent = new Intent(UnlockGesturePasswordActivity.this,
					           HomePageActivity.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				// 打开新的Activity
				startActivity(intent);
				finish();
			} else {
				mLockPatternView.setDisplayMode(LockPatternView.DisplayMode.Wrong);
				if (pattern.size() >= 

LockPatternUtils.MIN_PATTERN_REGISTER_FAIL) {
					mFailedPatternAttemptsSinceLastTimeout++;
					int retry = LockPatternUtils.FAILED_ATTEMPTS_BEFORE_TIMEOUT- mFailedPatternAttemptsSinceLastTimeout;
					if (retry >= 0) {
						if (retry == 0)
							showToast("您已5次输错密码，请30秒后再试");
						mHeadTextView.setText("密码错误，还可以再输入" + retry + "次");
						mHeadTextView.setTextColor(Color.RED);
						mHeadTextView.startAnimation(mShakeAnim);
					}

				}else{
					showToast("输入长度不够，请重试");
				}

				if (mFailedPatternAttemptsSinceLastTimeout >= 

LockPatternUtils.FAILED_ATTEMPTS_BEFORE_TIMEOUT) {
					mHandler.postDelayed(attemptLockout, 2000);
				} else {
					mLockPatternView.postDelayed(mClearPatternRunnable, 

2000);
				}
			}
		}

		private void patternInProgress() {
		}

		@Override
		public void onPatternCellAdded(List<Cell> pattern) {
			// TODO Auto-generated method stub
			
		}
	};
	Runnable attemptLockout = new Runnable() {

		@Override
		public void run() {
			mLockPatternView.clearPattern();
			mLockPatternView.setEnabled(false);
			mCountdownTimer = new CountDownTimer(
					LockPatternUtils.FAILED_ATTEMPT_TIMEOUT_MS + 1, 

1000) {
				@Override
				public void onTick(long millisUntilFinished) {
					int secondsRemaining = (int) (millisUntilFinished / 

1000) - 1;
					if (secondsRemaining > 0) {
						mHeadTextView.setText(secondsRemaining + " 秒后重试");
					} else {
						mHeadTextView.setText("请绘制手势密码");
						mHeadTextView.setTextColor(Color.WHITE);
					}
				}
				@Override
				public void onFinish() {
					mLockPatternView.setEnabled(true);
					mFailedPatternAttemptsSinceLastTimeout = 0;
				}
			}.start();
		}
	};
	
	@Override
	public void finish() {
		App.getInstance().getAllActivity().remove(this);
		super.finish();
	}
}
